package com.powergisol.gis.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.metadata.Sheet;
import com.powergisol.gis.Enum.ServiceTypeEnum;
import com.powergisol.gis.dao.*;
import com.powergisol.gis.dto.ExcelRectangularPillarModelDTO;
import com.powergisol.gis.entity.*;
import com.powergisol.gis.exception.GlobalExceptionHandler;
import com.powergisol.gis.listener.BoardExcelModelListener;
import com.powergisol.gis.listener.GirderExcelModelListener;
import com.powergisol.gis.listener.RectangularPillarModelListener;
import com.powergisol.gis.listener.StairsExcelModelListener;
import com.powergisol.gis.service.TabRectangularPillarService;
import com.powergisol.gis.util.FileUpload;
import com.powergisol.gis.util.FileUtil;
import com.powergisol.gis.util.Result;
import com.powergisol.gis.util.ZipUtil;
import com.powergisol.gis.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : laishihao
 * @date : 2020/11/12
 * description :
 */
@Service
public class TabRectangularPillarServiceImpl implements TabRectangularPillarService {

    @Value("${earth-url}")
    private String earthUrl;
    @Resource
    private TabMouldMapper tabMouldMapper;
    @Resource
    private TabDataSettingMapper tabDataSettingMapper;


    @Resource
    private CacheManager cacheManager;
    @Autowired
    private TabRectangularPillarMapper rectangularPillarMapper;
    @Autowired
    private BoardBasisMapper boardBasisMapper;
    @Autowired
    private TabGriderMapper griderMapper;
    @Autowired
    private TabGriderHighwidthMapper griderHighwidthMapper;
    @Autowired
    private TabGriderSteadyMapper griderSteadyMapper;
    @Autowired
    private TabStairsMapper stairsMapper;


    /**
     * 缓存数据检查线程池大小核心线程数
     */
    private static final int DEVICE_DATA_DISPOSE_THREAD_CORE_POOL_SIZE = 5;
    /**
     * 缓存数据检查线程池大小最大并发数
     */
    private static final int DEVICE_DATA_DISPOSE_THREAD_MAXIMUM_POOL_SIZE = 40;
    /**
     * 数据处理线程池最大待处理任务量
     */
    private static final int MAX_WAIT_TASK_COUNT = 5000;
    private static ThreadPoolExecutor excelDataDisposeThreadPool;

    static {
        excelDataDisposeThreadPool = new ThreadPoolExecutor(DEVICE_DATA_DISPOSE_THREAD_CORE_POOL_SIZE,
                DEVICE_DATA_DISPOSE_THREAD_MAXIMUM_POOL_SIZE,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(MAX_WAIT_TASK_COUNT), r -> {
            Thread thread = new Thread(r);
            thread.setDaemon(true);
            return thread;
        });
    }


    @Override
    public Result selectRectangularPillar(String uuid, String hcdm01) {
        return new Result().success(rectangularPillarMapper.selectByUuid(uuid, hcdm01));
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public Result excelImportZHU(MultipartFile excelFile, TabRectangularPillarVO vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();
        Integer serviceId = null;
        try {


            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile, userDir, uuid);
            userDir = (String) result.getData();

            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName() + sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl + serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.RECTANGULARPILLARDATA.getValue());
            tabServiceVo.setUuid(vo.getUuid());
            //保存服务
            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(), tabServiceVo.getId());

            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);
            TabCoordinateSystem system = new TabCoordinateSystem();
            if (1 == vo.getIsChange()) {
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                dataSetting.setCoorName(vo.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);
            //解压文件
            String zipUrl = userDir.substring(0, userDir.lastIndexOf(File.separator)) + File.separator + uuid;
            ZipUtil.unZip(userDir, zipUrl);


            ExcelRectangularPillarModelDTO rectangularPillarModelDTO = new ExcelRectangularPillarModelDTO();

            List<File> listFile = FileUtil.recursionFile(zipUrl, null);
            ExcelReader excelReader = null;

            Cache cache = cacheManager.getCache("cache-data");
            //成功条数
            AtomicInteger cgNum = new AtomicInteger();
            //失败数据
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            List<Future<?>> taskList = new ArrayList<>();
            for (File file : listFile) {
                String excelName = file.getName();
                excelReader = EasyExcel.read(file).build();
                List<Sheet> sheets = excelReader.getSheets();
                TabCoordinateSystem finalSystem = system;
                Future<?> task = excelDataDisposeThreadPool.submit(() -> {
                    try {
                        for (Sheet sheet : sheets) {
                            TabRectangularPillarVO vo1 = new TabRectangularPillarVO();
                            String sheetName = sheet.getSheetName();
                            BeanUtils.copyProperties(vo, vo1);
                            // vo1.setHcdm01(excelName);
                            vo1.setExcelName(excelName);
                            vo1.setSheetName(sheetName);
                            String beforeSheetName = sheet.getSheetName().substring(0, 2);
                            if (beforeSheetName.equals("Sh") || beforeSheetName.equals("LB")) {
                                continue;
                            } else {
                                RectangularPillarModelListener listener = new RectangularPillarModelListener(vo1, finalSystem, cacheManager,
                                        vo.getLon(), vo.getLat(), vo.getHigh(), rectangularPillarModelDTO);
//                                RectangularPillarModelListener listener = new RectangularPillarModelListener(vo1, finalSystem, p, cacheManager,
//                                        BigDecimal.valueOf(16229.652), BigDecimal.valueOf(102967.411), BigDecimal.valueOf(-20.30), rectangularPillarModelDTO);
                                EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet, listener);
                                if (null != cache.get(sheetName + uuid + "sb")) {
                                    TaskResultVo taskResultVo = cache.get(sheetName + uuid + "sb", TaskResultVo.class);
                                    listFailed.addAll(taskResultVo.getListFailed());
                                } else {
                                    cgNum.set(cgNum.get() + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new GlobalExceptionHandler(500,"数据解析失败");
                    }
                });
                taskList.add(task);
            }
            waitTaskListCompleted(taskList);
            //持久化excel数据
            rectangularPillarMapper.insertList(rectangularPillarModelDTO.getTabRectangularPillarsList());

            map.put("成功条数", cgNum);
            map.put("失败数据", listFailed);

        } catch (Exception e) {
            e.printStackTrace();
            //TODO 删除相应的数据
            /*if (null != serviceId) {
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }*/
            return result.failure(500, "服务器内部错误");
        }

        result.success(map);
        return result;
    }
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    @Override
    public Result excelImportLIANG(MultipartFile excelFile, TabGriderVO vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();
        Integer serviceId = null;


        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile, userDir, uuid);
            userDir = (String) result.getData();

            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName() + sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl + serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.GRIDER.getValue());
            tabServiceVo.setUuid(vo.getUuid());
            //保存服务
            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(), tabServiceVo.getId());

            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);

            TabCoordinateSystem system = new TabCoordinateSystem();
//            if (1 == vo.getIsChange()) {
//                system = tabMouldMapper.getCoorByName(vo.getCoorName());
//                //            dataSetting.setCoorName(vo.getCoorName());
//            }

            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);


            //解压文件
            String zipUrl = userDir.substring(0, userDir.lastIndexOf(File.separator)) + File.separator + uuid;
            ZipUtil.unZip(userDir, zipUrl);

            ExcelRectangularPillarModelDTO rectangularPillarModelDTO = new ExcelRectangularPillarModelDTO();

            List<File> listFile = FileUtil.recursionFile(zipUrl, null);
            ExcelReader excelReader = null;


            Cache cache = cacheManager.getCache("cache-data");
            //成功条数
            AtomicInteger cgNum = new AtomicInteger();
            //失败数据
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            List<Future<?>> taskList = new ArrayList<>();
            for (File file : listFile) {
                String excelName = file.getName();
                excelReader = EasyExcel.read(file).build();
                List<Sheet> sheets = excelReader.getSheets();
                TabCoordinateSystem finalSystem = system;
                Future<?> task = excelDataDisposeThreadPool.submit(() -> {
                    try {
                        for (Sheet sheet : sheets) {
                            TabGriderVO vo1 = new TabGriderVO();
                            String sheetName = sheet.getSheetName();
                            BeanUtils.copyProperties(vo, vo1);
                            vo1.setExcelName(excelName);
                            vo1.setSheetName(sheetName);
                            GirderExcelModelListener listener = new GirderExcelModelListener(vo1, finalSystem, cacheManager,
                                    vo.getLon(), vo.getLat(), vo.getHigh(), rectangularPillarModelDTO);
                            EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet, listener);
                            if (null != cache.get(sheetName + uuid + "sb")) {
                                TaskResultVo taskResultVo = cache.get(sheetName + uuid + "sb", TaskResultVo.class);
                                listFailed.addAll(taskResultVo.getListFailed());
                            } else {
                                cgNum.set(cgNum.get() + 1);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new GlobalExceptionHandler(500,"服务器错误，解析数据失败");
                    }
                });
                taskList.add(task);
            }
            waitTaskListCompleted(taskList);

            griderMapper.insertList(rectangularPillarModelDTO.getGridersList1());

            //创建接收数据的集合 （支座数据）
            List<TabGriderSteady> newGriderSteadyList = new ArrayList<>();
            //（连续梁高、宽）
            List<TabGriderHighwidth> griderHighwidthsList = new ArrayList<>();

            for (LinkedBlockingDeque<TabGriderHighwidth> griderHighwidths : rectangularPillarModelDTO.getGriderHighwidthList1()) {
                for (TabGriderHighwidth griderHighwidth : griderHighwidths) {
                    griderHighwidthsList.add(griderHighwidth);
                }
                if (griderHighwidthsList.size() == 500) {//如果达到500条，存储一次
                    int i = griderHighwidthMapper.insertList1(griderHighwidthsList);
                    if (i > 0) {//如果成功则清空该集合
                        griderHighwidthsList.clear();
                    }
                }
            }
            for (LinkedBlockingDeque<TabGriderSteady> griderSteadyList : rectangularPillarModelDTO.getGriderSteadyList1()) {
                for (TabGriderSteady griderSteady : griderSteadyList) {
                    newGriderSteadyList.add(griderSteady);
                }
                if (newGriderSteadyList.size() == 500) {
                    int i = griderSteadyMapper.insertList1(newGriderSteadyList);
                    if (i > 0) {
                        newGriderSteadyList.clear();
                    }
                }
            }
            //最后再执行一次剩下的数据
            griderHighwidthMapper.insertList1(griderHighwidthsList);
            griderSteadyMapper.insertList1(newGriderSteadyList);

            map.put("成功条数", cgNum);
            map.put("失败数据", listFailed);
        } catch (Exception e) {
            e.printStackTrace();
            //TODO 删除相应的数据
//            if(null != serviceId) {
//                tabDataSettingMapper.delTabDataSetting(serviceId);
//                tabDataSettingMapper.delTabService(serviceId);
//                tabDataSettingMapper.delUserService(serviceId);
//            }
            //开启了事务，当异常被捕获时，事务不会生效，只有throw一个新的异常就会触发事务的回滚。
            throw new GlobalExceptionHandler(500, "系统错误");
//            return result.failure(500, "系统错误");
        }

        result.success(map);
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public Result importBoard(MultipartFile file, TabRectangularPillarVO vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Integer serviceId = null;
        //返回消息
        Map<String, Object> map = new HashMap<>();
        //成功条数
        AtomicInteger cgNum = new AtomicInteger();
        //失败记录
        List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
        try {
            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");
            result = FileUpload.fileUpload(file, userDir, uuid);
            userDir = (String) result.getData();

            String fileName1 = file.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName() + sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl + serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.BOARD.getValue());
            tabServiceVo.setUuid(vo.getUuid());
            //保存服务
            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(), tabServiceVo.getId());

            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);
            TabCoordinateSystem system = new TabCoordinateSystem();
            if (1 == vo.getIsChange()) {
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                dataSetting.setCoorName(vo.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);

            //解压文件
            String zipUrl = userDir.substring(0, userDir.lastIndexOf(File.separator)) + File.separator + uuid;
            ZipUtil.unZip(userDir, zipUrl);

            if (1 == vo.getIsChange()) {
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
            }
            ExcelRectangularPillarModelDTO rectangularPillarModelDTO = new ExcelRectangularPillarModelDTO();

            List<File> listFile = FileUtil.recursionFile(zipUrl, null);
            Cache cache = cacheManager.getCache("cache-data");

            List<Future<?>> taskList = new ArrayList<>();
            BoardBasisEntity boardBasisEntity = new BoardBasisEntity();
            boardBasisEntity.setUuid(uuid);
            ExcelReader excelReader = null;
            for (File f : listFile) {
                if(f.getName().contains("~")){
                    continue;
                }
                excelReader = EasyExcel.read(f).build();
                List<Sheet> sheets = excelReader.getSheets();
                TabCoordinateSystem finalSystem = system;
                Future<?> submit = excelDataDisposeThreadPool.submit(() -> {
                    try {
                        for (Sheet sheet : sheets) {
                            String sheetName = sheet.getSheetName();
                            if (sheetName.contains("Y") || sheetName.contains("y")) {
                                continue;
                            }
                            BoardBasisEntity board = new BoardBasisEntity();
                            BeanUtils.copyProperties(boardBasisEntity, board);
                            vo.setExcelName(f.getName());
                            vo.setSheetName(sheet.getSheetName());
                            EasyExcel.readBySax(new FileInputStream(f.getAbsoluteFile()), sheet, new BoardExcelModelListener(board, vo, finalSystem, rectangularPillarModelDTO, cacheManager));
                            if (null != cache.get(sheetName + uuid + "board")) {
                                TaskResultVo taskResultVo = cache.get(sheetName + uuid + "board", TaskResultVo.class);
                                listFailed.addAll(taskResultVo.getListFailed());
                            } else {
                                cgNum.set(cgNum.get() + 1);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new GlobalExceptionHandler(500, "数据解析失败");
                    }
                });
                taskList.add(submit);
            }
            if (excelReader != null) {
                excelReader.finish();
            }
            waitTaskListCompleted(taskList);

            LinkedBlockingDeque<BoardBasisEntity> basisEntities = rectangularPillarModelDTO.getBasisEntities();
            boardBasisMapper.saveBatch(basisEntities);

            map.put("成功条数", cgNum);
            map.put("失败数据", listFailed);

        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalExceptionHandler(500, "数据解析失败");
        }
        result.success(map);
        return result;
    }

    @Override
    public Result excelImportStairs(MultipartFile excelFile, TabStairsVO vo, TabUserVo tabUserVo) {
        Result result = new Result();
        Map<String, Object> map = new HashMap<>();
        Integer serviceId = null;
        try {


            String uuid = vo.getUuid();
            String userDir = System.getProperty("user.dir");

            //上传文件
            result = FileUpload.fileUpload(excelFile, userDir, uuid);
            userDir = (String) result.getData();

            String fileName1 = excelFile.getName();
            vo.setFileName(fileName1);
            // 获取文件名
            String fileName = excelFile.getOriginalFilename();
            // 获取文件的后缀名
            vo.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));

            //发布服务
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
            String serviceName = vo.getFileName() + sdf1.format(new Date());
            TabServiceVo tabServiceVo = new TabServiceVo();
            tabServiceVo.setServiceUrl(earthUrl + serviceName);
            //根据用户查询用户
            tabServiceVo.setUserId(tabUserVo.getId());

            tabServiceVo.setName(serviceName);
            tabServiceVo.setReleaseTime(new Date());
            tabServiceVo.setServiceType(ServiceTypeEnum.STAIRS.getValue());
            tabServiceVo.setUuid(vo.getUuid());
            //保存服务
            tabDataSettingMapper.saveService(tabServiceVo);
            tabDataSettingMapper.saveUserService(tabServiceVo.getUserId(), tabServiceVo.getId());

            serviceId = tabServiceVo.getId();
            TabDataSetting dataSetting = new TabDataSetting();
            dataSetting.setUuid(vo.getUuid());
            dataSetting.setCreateUser(tabUserVo.getName());
            dataSetting.setDataType(1);
            dataSetting.setDataUrl(userDir);
            dataSetting.setCreateTime(new Date());
            dataSetting.setServiceId(serviceId);
            TabCoordinateSystem system = new TabCoordinateSystem();
            if (1 == vo.getIsChange()) {
                system = tabMouldMapper.getCoorByName(vo.getCoorName());
                dataSetting.setCoorName(vo.getCoorName());
            }
            //保存入库
            tabDataSettingMapper.saveDataSetting(dataSetting);
            //解压文件
            String zipUrl = userDir.substring(0, userDir.lastIndexOf(File.separator)) + File.separator + uuid;
            ZipUtil.unZip(userDir, zipUrl);


            ExcelRectangularPillarModelDTO rectangularPillarModelDTO = new ExcelRectangularPillarModelDTO();

            List<File> listFile = FileUtil.recursionFile(zipUrl, null);
            ExcelReader excelReader = null;

            Cache cache = cacheManager.getCache("cache-data");
            //成功条数
            AtomicInteger cgNum = new AtomicInteger();
            //失败数据
            List<ExcelInFailedDataVo> listFailed = new ArrayList<>();
            List<Future<?>> taskList = new ArrayList<>();
            for (File file : listFile) {
                String excelName = file.getName();
                excelReader = EasyExcel.read(file).build();
                List<Sheet> sheets = excelReader.getSheets();
                TabCoordinateSystem finalSystem = system;
                Future<?> task = excelDataDisposeThreadPool.submit(() -> {
                    try {
                        for (Sheet sheet : sheets) {
                            TabStairsVO vo1 = new TabStairsVO();
                            String sheetName = sheet.getSheetName();
                            BeanUtils.copyProperties(vo, vo1);
                            // vo1.setHcdm01(excelName);
                            vo1.setExcelName(excelName);
                            vo1.setSheetName(sheetName);
                            String beforeSheetName = sheet.getSheetName().substring(0, 2);
                            if (beforeSheetName.equals("Sh") || beforeSheetName.equals("LB")) {
                                continue;
                            } else {
                                StairsExcelModelListener listener = new StairsExcelModelListener(vo1, finalSystem, cacheManager,
                                        vo.getLon(), vo.getLat(), vo.getHigh(), rectangularPillarModelDTO);
                                EasyExcelFactory.readBySax(new FileInputStream(file.getAbsolutePath()), sheet, listener);
                                if (null != cache.get(sheetName + uuid + "sb")) {
                                    TaskResultVo taskResultVo = cache.get(sheetName + uuid + "sb", TaskResultVo.class);
                                    listFailed.addAll(taskResultVo.getListFailed());
                                } else {
                                    cgNum.set(cgNum.get() + 1);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new GlobalExceptionHandler(500,"数据解析失败");
                    }
                });
                taskList.add(task);
            }
            waitTaskListCompleted(taskList);
            //持久化excel数据
            stairsMapper.insertList(rectangularPillarModelDTO.getStairsList());

            map.put("成功条数", cgNum);
            map.put("失败数据", listFailed);

        } catch (Exception e) {
            e.printStackTrace();
            //TODO 删除相应的数据
            /*if (null != serviceId) {
                tabDataSettingMapper.delTabDataSetting(serviceId);
                tabDataSettingMapper.delTabService(serviceId);
                tabDataSettingMapper.delUserService(serviceId);
            }*/
            return result.failure(500, "系统错误");
        }

        result.success(map);
        return result;
    }


    private void waitTaskListCompleted(List<Future<?>> list) throws InterruptedException {
        int finash;
        do {
            finash = 0;
            for (Future<?> future : list) {
                if (future.isDone()) {
                    finash++;
                }
            }
            Thread.sleep(100);
        } while (finash < list.size());
    }
}
